package utils

import (
	"fmt"

	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/gconv"
)

const (
	URL_STATUS_UNCRAWLED  = 0
	URL_STATUS_CRAWLED    = 1
	URL_STATUS_FAIL       = 2
	URL_STATUS_PROCESSING = 3
	PORT_LIST_REDIS       = "web_driver_port"
	TXT2IMG_TASK          = "txt2img_task"
)

func RedisSetItemStatus(url string, status int) {

	conn := g.Redis().Conn()
	defer conn.Close()
	conn.Do("SET", url, status)
}

func RedisGetItemStatus(url string) (int, error) {
	conn := g.Redis().Conn()
	defer conn.Close()
	val, err := conn.DoVar("GET", url)
	if err != nil {
		return -1, err
	}
	return val.Int(), nil
}

func initRedisPort() {
	conn := g.Redis().Conn()
	defer conn.Close()

	arPort := make([]interface{}, 0)

	startPort := g.Cfg().GetInt("chromedriver.taskport_start")

	arPort = append(arPort, PORT_LIST_REDIS)

	for i := 0; i < 100; i++ {
		port := i + startPort
		portstr := gconv.String(port)
		arPort = append(arPort, portstr)
	}
	_, err := conn.Do("LPUSH", arPort...)
	if err != nil {
		fmt.Println("init port reids fail : ", err)
	}
	return

}

func RedisGetValidPort() int {
	conn := g.Redis().Conn()
	defer conn.Close()

	v, err := conn.Do("EXISTS", PORT_LIST_REDIS)
	if err != nil {
		return -1
	}
	if gconv.Int(v) == 0 {
		initRedisPort()
	}

	v, err = conn.Do("LPOP", PORT_LIST_REDIS)
	if err != nil {
		return -1
	}
	str := gconv.String(v)
	return gconv.Int(str)
}

func RedisReleasePort(port int) {
	conn := g.Redis().Conn()
	defer conn.Close()
	_, err := conn.Do("RPUSH", PORT_LIST_REDIS, gconv.String(port))
	if err != nil {
		fmt.Println("RedisReleasePort fail ", err)
	}
}

// 把任务存进hash表

func SetTxt2ImgTaskToRedis(taskId string, data string) error {
	conn := g.Redis().Conn()
	defer conn.Close()
	_, err := conn.Do("HSET", TXT2IMG_TASK, taskId, data)
	if err != nil {
		return err
	}
	return nil

}

func GetTxt2ImgTaskFromRedis(taskId string) (string, error) {
	conn := g.Redis().Conn()
	defer conn.Close()
	data, err := conn.DoVar("HGET", TXT2IMG_TASK, taskId)
	if err != nil {
		return "", err
	}
	return data.String(), nil
}
